package com.itheima.reggie.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.*;
import com.itheima.reggie.mapper.*;
import com.itheima.reggie.service.CartService;
import com.itheima.reggie.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private CartService cartService;
    @Autowired
    private AddressMapper addressMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;

    /**
     * 下订单新增订单
     *
     * @param order
     */
    @Override
    public void addOrder(Order order) {
        //获取登录人user对象
        User user = UserHolder.get();
        if (user == null) {
            throw new CustomException("用户未登录，不能下单");
        }
        //查询收货地址对象
        Address address = addressMapper.selectById(order.getAddressId());
        if (address == null) {
            throw new CustomException("收货地址为空，不能下单");
        }
        // 购物车不为空
//        LambdaQueryWrapper<Cart> cartQW = new LambdaQueryWrapper<>();
//        cartQW.eq(Cart::getUserId, UserHolder.get().getId());
//        List<Cart> cartList = cartMapper.selectList(cartQW);
        List<Cart> cartList = cartService.list();
        if (cartList == null) {
            throw new CustomException("购物车为空，不能下单");
        }
        long orderId = IdUtil.getSnowflake(1, 1).nextId();
        order.setId(orderId);
        order.setNumber(StrUtil.toString(orderId));
        order.setUserId(UserHolder.get().getId());
        order.setOrderTime(new Date());
        order.setCheckoutTime(new Date());
        //设置金额 遍历购物车相加

        BigDecimal amount = new BigDecimal(0);
        for (Cart cart : cartList) {
            //设置金额
//            BigDecimal amount1 = cart.getAmount();
//            BigDecimal number = new BigDecimal(cart.getNumber());
//            BigDecimal sum = amount1.multiply(number);
//            amount.add(sum);
            amount = amount.add(cart.getAmount().multiply(new BigDecimal(cart.getNumber())));
            // 处理新增order_detail表
            OrderDetail od = new OrderDetail();
            BeanUtil.copyProperties(cart, od);
            od.setId(null);
            od.setOrderId(order.getId());
            orderDetailMapper.insert(od);
        }
        order.setAmount(amount);
        //设置手机
        order.setPhone(address.getPhone());
        order.setAddress(address.getDetail());
        order.setUserName(UserHolder.get().getName());
        order.setConsignee(address.getConsignee());
        // 存入数据库表order
        orderMapper.insert(order);
        // 清空购物车
        cartService.clean();
    }

    /**
     * 历史订单
     *
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public Page<Order> orderPage(Integer page, Integer pageSize) {
        // 构建分页
        Page<Order> orderPage = new Page<>(page, pageSize);
        // 构建查询条件
        LambdaQueryWrapper<Order> qw = new LambdaQueryWrapper<>();
        qw.eq(Order::getUserId, UserHolder.get().getId());
        qw.orderByDesc(Order::getOrderTime);
        orderPage = orderMapper.selectPage(orderPage, qw);
        List<Order> orderList = orderPage.getRecords();
        for (Order order : orderList) {
            // 把订单明细封装进去, 每个订单的明细是什么
            LambdaQueryWrapper<OrderDetail> orderDetailQW = new LambdaQueryWrapper<>();
            orderDetailQW.eq(OrderDetail::getOrderId, order.getId());
            List<OrderDetail> orderDetails = orderDetailMapper.selectList(orderDetailQW);
            //把明细封装进order
            order.setOrderDetails(orderDetails);
        }
        return orderPage;
    }

    /**
     * 条件查询订单
     *
     * @param page
     * @param pageSize
     * @param number
     * @param orderTimeBegin
     * @param orderTimeEnd
     * @return
     */
    @Override
    public Page<Order> orderList(Integer page, Integer pageSize, Long number, Date orderTimeBegin, Date orderTimeEnd) {
        // 构建分页 select * from order where number = ? or order_time between ? and ?
        Page<Order> orderPage = new Page<>(page, pageSize);
        // 构建条件
        LambdaQueryWrapper<Order> qw = new LambdaQueryWrapper<>();
        qw.eq(number !=null,Order::getNumber, number);
        qw.between(orderTimeBegin!=null && orderTimeEnd!=null,Order::getOrderTime, orderTimeBegin, orderTimeEnd);
        return orderMapper.selectPage(orderPage, qw);
    }
}
